﻿using System;
using System.Linq;
using GoFishWeb.Models;

namespace GoFishWeb
{
	public partial class Statics : System.Web.UI.Page
	{
		protected void Page_Load(object sender, EventArgs e)
		{
            if (IsPostBack) return;
            if (Request.UrlReferrer == null) Response.Redirect("~/Default.aspx");
            using(var db = new GoFishContext())
            {
                gvStats.DataSource = db.PlayerRecords.ToList();
                gvStats.DataBind();

                CompletedGamesListBox.DataTextField = "Name";
                CompletedGamesListBox.DataValueField = "Id";
                CompletedGamesListBox.DataSource = db.Games.Where(x => x.IsGameOver).ToList();
                CompletedGamesListBox.DataBind();

                if (!db.Games.Any(x => x.IsGameOver)) return;
                CompletedGamesListBox.SelectedIndex = 0;

                var gameId = int.Parse(CompletedGamesListBox.SelectedValue);
                UpdateMoves(gameId, db);
                UpdateBooks(gameId, db);
            }
        
		}

        protected void CompletedGamesListBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                var gameId = int.Parse(CompletedGamesListBox.SelectedValue);
                UpdateMoves(gameId, new GoFishContext());
                UpdateBooks(gameId, new GoFishContext());
            }            
            catch (FormatException)
            {
                lblErrorMessage.Visible = true;
                lblErrorMessage.Text = "Please select a game.";
            }
        }

        private void UpdateMoves(int gameId, GoFishContext db)
        {
            var move = db.Games.Where(x => x.Id == gameId).Select(x => x.Moves).ToList();
            foreach( var moveList in move)
            {
                GameMovesListBox.DataTextField = "Description";
                GameMovesListBox.DataSource = moveList;
                GameMovesListBox.DataBind();
            }
            
        }

        private void UpdateBooks(int gameId, GoFishContext db)
        {
            BooksListBox.Items.Clear();
            var books = db.Games.Where(x => x.Id == gameId).Select(x => x.Books).ToList().FirstOrDefault();
            if (books == null) return;
            foreach (var b in books)
            {
                BooksListBox.Items.Add(string.Format("{0} had a book of {1}", b.PlayerName, Card.Plural(b.Rank)));
                BooksListBox.DataBind();
            }
        }

	}
}